package com.gzu.shop.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 利用反射判断为null的属性值, 一旦调用这个函数，就会触发，get函数
 */
public class ObjectPropertyUtil {
    public static Map<String, Object> getNoNullProperty(Object object) {
        Class<?> objectClass = object.getClass();

        HashMap<String, Object> hashMap = new HashMap<>();

        Method[] methods = objectClass.getDeclaredMethods();
        for (Method method : methods) {

            try {
                String name = method.getName();
                if (name.startsWith("get")) {
                    Object value = method.invoke(object);
                    if (!ObjectUtil.isEmpty(value)) {
                        String key = StrUtil.toUnderlineCase(name.substring(3));
                        System.out.println(name);
                        hashMap.put(key, value);
                    }
                }
            } catch (IllegalAccessException | InvocationTargetException e) {
               e.printStackTrace();
            }
        }

        return hashMap;
    }
}






